package com.example.myjavaapp.util;


import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;

public class HttpUtil {
    public static String httpGet(String urlStr) throws IOException {
        StringBuilder sb =new StringBuilder();
        BufferedReader reader = null;
        try{
            SSLContext sslcontext =SSLContext.getInstance("SSL");
            TrustManager [] tm ={new HttpX509TrustManager()};
            sslcontext.init(null,tm,new SecureRandom());
            HostnameVerifier ignoreHostnameVerifier = (s, sslSession) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            URL url =new URL(urlStr);
            HttpURLConnection connection =(HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.connect();
            int code =connection.getResponseCode();
            if(code == HttpURLConnection.HTTP_OK){
                reader =new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String temp;
                while ((temp =reader.readLine())!=null){
                    sb.append(temp);
                }
            }
            connection.disconnect();
        } catch (Exception e) {
            return e.getMessage();
        }finally {
            reader.close();
        }
        return sb.toString();
    }
}
